#!/bin/bash

# 快速上传到Diawi脚本
# 使用方法: ./quick_upload.sh [apk文件路径]

set -e

DIAWI_TOKEN="z1EH0NMJgFBt9wKES8UYny1PlxpVvczVriqrf1Scv6"

# 颜色输出
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m'

print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 如果没有提供文件路径，查找默认APK文件
if [ $# -eq 0 ]; then
    APK_PATH="build/app/outputs/flutter-apk/app-release.apk"
    if [ ! -f "$APK_PATH" ]; then
        print_error "默认APK文件不存在: $APK_PATH"
        print_info "请先运行: flutter build apk --release"
        exit 1
    fi
else
    APK_PATH=$1
fi

if [ ! -f "$APK_PATH" ]; then
    print_error "文件不存在: $APK_PATH"
    exit 1
fi

print_info "上传文件: $APK_PATH"
print_info "文件大小: $(ls -lh "$APK_PATH" | awk '{print $5}')"

# 上传到Diawi
response=$(curl -s -X POST \
    -F "token=$DIAWI_TOKEN" \
    -F "file=@$APK_PATH" \
    -F "comment=快速上传 - $(date '+%Y-%m-%d %H:%M:%S')" \
    "https://upload.diawi.com/")

# 获取job ID
if command -v jq &> /dev/null; then
    job_id=$(echo "$response" | jq -r '.job // empty')
else
    job_id=$(echo "$response" | sed -n 's/.*"job":"\([^"]*\)".*/\1/p')
fi

if [ -z "$job_id" ] || [ "$job_id" = "null" ]; then
    print_error "上传失败"
    echo "$response"
    exit 1
fi

print_success "上传成功，任务ID: $job_id"
print_info "正在处理，请稍候..."

# 检查状态
for i in {1..30}; do
    sleep 5
    status_response=$(curl -s "https://upload.diawi.com/status?token=$DIAWI_TOKEN&job=$job_id")
    
    if command -v jq &> /dev/null; then
        status=$(echo "$status_response" | jq -r '.status // "unknown"')
        if [ "$status" = "2000" ]; then
            link=$(echo "$status_response" | jq -r '.link')
            break
        elif [ "$status" = "4000" ]; then
            print_error "处理失败"
            exit 1
        fi
    else
        if echo "$status_response" | grep -q '"status":2000'; then
            link=$(echo "$status_response" | sed -n 's/.*"link":"\([^"]*\)".*/\1/p')
            break
        elif echo "$status_response" | grep -q '"status":4000'; then
            print_error "处理失败"
            exit 1
        fi
    fi
    
    echo -n "."
done

echo ""

if [ -n "$link" ]; then
    print_success "🎉 处理完成！"
    echo ""
    echo "🔗 安装链接: $link"
    echo ""
    
    # 保存链接
    echo "$link" >> "diawi_links.txt"
    print_info "链接已保存到 diawi_links.txt"
    
    # 如果是macOS，尝试复制到剪贴板
    if [[ "$OSTYPE" == "darwin"* ]] && command -v pbcopy &> /dev/null; then
        echo "$link" | pbcopy
        print_info "链接已复制到剪贴板"
    fi
else
    print_error "处理超时或失败"
    exit 1
fi 